﻿using System;
using AzureDiagMon.Common;
using Ninject.Activation;

namespace AzureDiagMon.Model
{
    public class DataContextProvider : IProvider<IModelsContainer>
    {
        private Type ModelsContainerType { get; set; }
        private IModelsContainer StaticContext { get; set; }
        public delegate IModelsContainer CreateModelsContainerDelegate();
        private CreateModelsContainerDelegate ActionToCreateContext { get; set; }

        private IModelsContainer CreateDataContext()
        {
            if (StaticContext != null)
                return StaticContext;

            if (ActionToCreateContext != null)
                return ActionToCreateContext();

            if (ModelsContainerType != null)
            {
                return Activator.CreateInstance(ModelsContainerType) as IModelsContainer;
            }
            return null;
        }

        public DataContextProvider()
        {
            ModelsContainerType = typeof(ModelsContainer);
        }

        public void SetContextType(Type modelsContainerType)
        {
            ModelsContainerType = modelsContainerType;
        }

        public void SetContextCreator(CreateModelsContainerDelegate actionToCreateContext)
        {
            ActionToCreateContext = actionToCreateContext;
        }

        public void SetStaticContext(IModelsContainer context)
        {
            StaticContext = context;
        }

        #region Implementation of IProvider

        public object Create(IContext context)
        {
            return CreateDataContext();
        }

        public Type Type
        {
            get { return typeof (IModelsContainer); }
        }

        #endregion
    }

}
